<?php

namespace App\Jobs;


use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\Msg;
use App\Libraries\Tools\URL;
use App\Models\HongBao\HongBao;
use App\Models\Msg\MsgSystem;
use App\Models\User\User;
use Illuminate\Support\Facades\Log;
use JPush\Client;

class PushMsgJob extends Job
{


    private $to_ids;
    private $msg;
    private $type;
    private $ext;


    public function __construct(array $to_ids, $msg, $type, $ext=null)
    {
        $this->to_ids = $to_ids;
        $this->msg = $msg;
        $this->type = $type;//type 0-普通消息 1-红包信息 2-VIP过期信息 3-auth改变 4-agent改变 5-manager改变
        $this->ext = $ext;
    }

    /**
     * Execute the job.
     *
     * @return bool
     * @throws \Exception
     */
    public function handle()
    {
        try{
            if(!is_array($this->to_ids)){
                return false;
            }
            foreach($this->to_ids as $k => $v){
                if(is_string($v)){
                    continue;
                }
                $this->to_ids[$k] = "$v";
            }
            if(is_null($this->ext)){
                $ext = ['user_id'=>6, 'type'=>$this->type];
            }else{
                $ext = $this->ext;
            }
            $user = User::where('user_id', $ext['user_id'])->first();
            if(!empty($user)){
                $ext['cover'] = URL::getImage($user->cover);
                $ext['nickname'] = $user->nickname;
            }
            $client = new Client(env('JIGUANG_APPID'), env('JIGUANG_SECRET'), null);
            $client->push()//发送真实环境
                ->setPlatform(['ios','android'])
                ->addAlias($this->to_ids)
                ->addAndroidNotification($this->msg, '夜城', 1, $ext)
                ->addIosNotification($this->msg, 'iOS sound', '+1', null, null, $ext)
                ->setOptions(100000, 3600, null, true)
                ->send();
            $client->push()//发送测试环境
                ->setPlatform(['ios'])
                ->addAlias($this->to_ids)
                ->addIosNotification($this->msg, 'iOS sound', '+1', null, null, $ext)
                ->setOptions(100000, 3600, null, false)
                ->send();
        }catch (\Exception $e){
//            throw new \Exception($e);
            return false;
        }
        return true;
    }
}
